package mysql

import (
	"gorm.io/gorm"
	"hemabox/hemarpc/hemarpc"
)

type Hema struct {
	gorm.Model
	HemaName    string  `gorm:"type:varchar(30);not null"`
	HemaContent string  `gorm:"type:varchar(50);not null"`
	HemaPrice   float64 `gorm:"type:decimal(10,2);not null"`
	HemaClassId int     `gorm:"type:int;not null"`
}

func (h *Hema) HemaAdd(db *gorm.DB) error {
	return db.Debug().Create(h).Error
}

func (h *Hema) FindHemaByHemaName(db *gorm.DB, name string) error {
	return db.Debug().Where("hema_name=?", name).First(&h).Error
}

func HemaList(db *gorm.DB, in *hemarpc.HemaListRequest) ([]*hemarpc.HemaList, error) {
	/*
		SELECT
		  hemas.id as hema_id,
		  hemas.hema_name,
		  hemas.hema_content,
		  hemas.hema_price,
		  classes.id as class_id,
		  classes.class_name
		FROM
		  hemas
		  LEFT JOIN classes ON hemas.hema_class_id = classes.id
	*/
	var list []*hemarpc.HemaList
	err2 := db.Debug().Model(&Hema{}).
		Select(
			"hemas.id as hema_id",
			"hemas.hema_name",
			"hemas.hema_content",
			"hemas.hema_price",
			"classes.id as class_id",
			"classes.class_name",
		).
		Joins("LEFT JOIN classes ON hemas.hema_class_id = classes.id").
		Scopes(Paginate(int(in.Page), int(in.Size))).Find(&list).Error
	return list, err2
}
